const defaultKv = {
  id: "id",
  pid: "pid",
  label: "label",
  value: "value",
  children: ""
};
const defaultPid = "pid";
const defaultChildrenKey = "children";



const toTreeData = (data, kv, pid, childrenKey) => {//找到当前组织的直系子节点
    // 建立个树形结构,需要定义个最顶层的父节点，pId是1
  if(kv == null)kv = defaultKv;
  if(pid == null)pid = defaultPid;
  if(childrenKey == null)childrenKey = defaultChildrenKey;
  let parent = [];
  for (let i = 0; i < data.length; i++) {
      let pidVal = "" + data[i][pid];
      if (pidVal != '0') {
      } else {
          let obj = {};
          Object.keys(kv).forEach((item) => {
              if(item == childrenKey){
              }else{
                  obj[item] = data[i][kv[item]];
              }
          });
          parent.push(obj); //数组加数组值
      }
  }
  children(parent, data, kv, pid, childrenKey);
  return parent;
};
const children = (parent, data, kv, pid, childrenKey) => {//给当前组织的直系子节点添加剩下的子节点
    if (data && parent) {
        for (let i = 0; i < parent.length; i++) {
            for (let j = 0; j < data.length; j++) {
                if (parent[i].id == data[j][pid]) {
                    let obj = {};
                    Object.keys(kv).forEach((item) => {
                        if(item == childrenKey){
                        }else{
                            obj[item] = data[j][kv[item]];
                        }
                    });
                    if(parent[i][childrenKey]){
                    }else{
                        parent[i][childrenKey] = [];
                    }
                    parent[i][childrenKey].push(obj);
                }
            }
            children(parent[i][childrenKey], data, kv, pid, childrenKey);
        }
    }
};

export default toTreeData;
